<template>
	<view class="box">
		<view class="row">
			<text>手机号</text>
			<input type="text" v-model="phone" maxlength="12"/>
		</view>
		<view class="row">
			<view class="send">
				<button class="captcha" size="mini" :disabled="!tagCode" 
				@click="sendCode">验证码</button>
				<text>{{number}}</text>
			</view>
			<input type="text" v-model="code"  placeholder="- - - -" maxlength="4" />
		</view>
		<view class="row">
			<text style="font-size: 23rpx;">收不到验证码？试试 <text style="color:#00BB00;font-size: 23rpx;"> 语音验证</text></text>
			<!--   -->
			<button type="primary" style="width: 90%;border-radius: 80rpx;margin-top: 50rpx;"
			@click="login"
			:disabled="!tagLogin"
			>登录</button>
		</view>
		<view class="row">
			<text style="color: #006699;text-align: center;" >通过微信授权登录</text>
		</view>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				phone:"",		//用户输入的手机号
				code:"",			//用户输入的验证码
				tagCode:false,			//false 验证码按钮不可点击；true 可以点击
				tagLogin:false,			//false 登录按钮禁用；true 按钮启用
				number:""
			}
		},
		watch:{
			phone:function(newValue){
				let result =/^1[35789]\d{9}$/.test(newValue);
				this.tagCode=result;
			},
			code:function(newValue){
				//检测用户输入的验证码，如果验证码长度等于4，则登录按钮启用；否则禁用登录按钮
				if(newValue.length==4){
					this.tagLogin=true
				}else{
					this.tagLogin=false;
				}
			}
		},
		methods:{
			//点击按钮，发送验证码
			async sendCode(){
				//进行倒计时
				this.number=5;
				this.tagCode=false;		//应用验证码按钮
				let timer=setInterval(()=>{
					this.number-=1;
					if(this.number<=0){
						clearInterval(timer);
						this.number=""
						this.tagCode=true;
					}
				},1000)
				//调用接口，给用户发短信+http返回正确的验证码
				let result =await this.$http({url:"/api/sms",data:{
					phone:this.phone
				}}).catch(err=>console.error(err))
				
				// 获取到正确的验证码，存储在客户端
				uni.setStorageSync("code",result.data.list.code)
			},
			//执行登录
			async login(){
				//判断验证码是否正确
				let localCode=uni.getStorageSync("code");
				if(this.code==localCode){
					//验证码正确，请求登录的接口，获取uid和token
					let result = await this.$http({url:"/api/wxlogin",data:{phone:this.phone}})
					.catch(err=>{
						console.error(err)
					})
					// 把用户信息存储在缓存
					uni.setStorageSync("userInfo",result.data.list)
					uni.reLaunch({
						url:"/pages/mine/mine"
					})
					
				}else{
					uni.showToast({
						title:"验证码错误",
						icon:"none"
					})
				}
			}
		}
	}
</script>

<style>
	/* 导入外部的样式文件 */
	/* @import url("../../common/css/index.css"); */
	.box{
		position: relative;
	}

	.row{
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		margin: 40rpx;
	}
	.send{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.send text:nth-of-type(2){
		color: #00BB00;
	}
	text{
		font-size: 27rpx;
		margin-bottom: 10rpx;
	}
	input{
		border-bottom: 1rpx solid gray;
		height: 65rpx;
	}
	.captcha{
		background: #007cfe;
		color: white;
		padding: 10rpx 20rpx;
		border-radius: 13rpx;
		margin: 0rpx;
	}
</style>
